package com.ganinfo.common.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ganinfo.common.Logger;
import com.ganinfo.common.Result;
import com.ganinfo.common.annotation.IgnoreAuth;
import com.ganinfo.common.constant.PropertiesConstant;
import com.ganinfo.common.data.TransmitMap;
import com.ganinfo.common.redis.RedisUtils;
import com.ganinfo.common.token.IToken;
import com.ganinfo.common.token.TokenFactory;
import com.xiaoleilu.hutool.date.DateUtil;

public class LogInterceptor implements HandlerInterceptor {

	protected Logger logger = Logger.getLogger(this.getClass());

	private final String env = PropertiesConstant.BTSQL_EXT_PRO.getStr("PRODUCT_MODE");// 当前环境测试还是正式;
	/**
	 * controller执行后且视图返回后调用此方法 这里可得到执行controller时的异常信息 这里可记录操作日志，资源清理等
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		if ("false".equals(env)) {// 开发环境
			logger.info("--------------------" + DateUtil.now()+ " 结束-------------------------------------");
			logger.info("");
		}
	}

	/**
	 * controller执行后但未返回视图前调用此方法 这里可在返回用户前对模型数据进行加工处理，比如这里加入公用信息以便页面显示
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * controller执行前调用此方法 返回true表示继续执行，返回false中止执行 这里可以加入登录校验、权限拦截等
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		boolean flag=true;
		response.setHeader("Access-Control-Allow-Origin", "*");
		if ("false".equals(env)) {// 开发环境
			logger.info("");
			logger.info("--------------------" + DateUtil.now()+ " 开始-------------------------------------");
			logger.info("ip地址:" + request.getRemoteAddr());
			logger.info("接口地址:" + request.getServletPath());
			logger.info("参数列表:" + new TransmitMap(request));
		}
		if(!PropertiesConstant.CONFIG_PRO.getBool("notoken", false)){//判断是否屏蔽全局token
			IgnoreAuth annotation;
			if (handler instanceof HandlerMethod) {
				annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
				// 如果有@IgnoreAuth注解，则不验证token
				if (annotation == null) {
					String token = request.getParameter(PropertiesConstant.CONFIG_PRO.getStr("paramToken"));
					if("commtoken".equals(token)){
						request.setAttribute("userCode", "admin");
					}else if(token==null){
						response.setContentType("text/json;charset=UTF-8");
						String result;
						result = new Result(401, null, "token传递为空！", null).toJson();
						PrintWriter out = response.getWriter();
						out.write(result);
						out.close();
						flag=false;
					}else{
						IToken itoken = TokenFactory.getToken(PropertiesConstant.CONFIG_PRO.getStr("cacheType"), null);
						boolean isnouse = itoken.validate(token);
						if (!isnouse) {// token失效
							response.setContentType("text/json;charset=UTF-8");
							String result;
							result = new Result(401, null, "登录超时，请重新登录！", null).toJson();
							PrintWriter out = response.getWriter();
							out.write(result);
							out.close();
							flag=false;
						}
						// 设置userId到request里，后续根据userId，获取用户信息
						request.setAttribute("userCode", RedisUtils.get(token));
					}
					
				}
			} 
		}
		return flag;
	}

}
